package action

import (
	"context"
	"gitee.com/dromara/carbon/v2"
	"server/component"
	"server/im/entity"
	"server/im/online"
	"server/im/protocol"
	"server/service"
)

// 登录成功
func EventLogin(event any) {
	eventRequest, ok := event.(entity.EventRequest)
	if !ok {
		component.Log.Error("bad event", event)
		return
	}
	userModel := eventRequest.Data.(entity.UserModel)
	//修改在线状态
	service.Us.ChangeOnline(context.Background(), &service.ChangeOnlineOpt{
		UserUni: userModel.Uuid,
		Event:   service.OnlineStatusOnline,
		Gateway: eventRequest.GatewayId,
	})
	isUserOnline := online.OnlineMap.IsUserOnline(userModel)

	//修改在线情况
	online.OnlineMap.Add(eventRequest.GatewayId, userModel)
	//广播上线消息
	if !isUserOnline {
		msgBytes, _ := component.JsonEncode(map[string]any{
			"uuid": userModel.Uuid,
			"name": userModel.Name,
			"time": carbon.Now().ToDateTimeString(),
		})
		eventRequest.RespondChan <- entity.CoreResultModel{
			CoreOutModel: entity.CoreOutModel{
				GatewayOutModel: entity.GatewayOutModel{
					Data: msgBytes,
					Cmd:  protocol.RespChatroomOnline,
				},
				GatewayId:    eventRequest.GatewayId,
				MsgType:      entity.MsgTypeNormal,
				ReceiverType: entity.ReceiverTypeExclude,
				Clients:      []string{userModel.Uuid},
			},
			ResultType: entity.CoreResultTypeAll,
		}
	}
}

// 用户下线
func EventOffline(event any) {
	eventRequest, ok := event.(entity.EventRequest)
	if !ok {
		component.Log.Error("bad event", event)
		return
	}
	userModel := eventRequest.Data.(entity.UserModel)
	//查看在线
	if online.OnlineMap.IsUserOnline(userModel) {
		//修改在线状态
		err := service.Us.ChangeOnline(context.Background(), &service.ChangeOnlineOpt{
			UserUni: userModel.Uuid,
			Event:   service.OnlineStatusOffLine,
			Gateway: eventRequest.GatewayId,
		})
		if err != nil {
			component.Log.Error("offline err", err)
			return
		}
		online.OnlineMap.Remove(eventRequest.GatewayId, userModel)
	}

	//广播下线消息
	if !online.OnlineMap.IsUserOnline(userModel) {
		msgBytes, _ := component.JsonEncode(map[string]any{
			"uuid": userModel.Uuid,
			"name": userModel.Name,
			"time": carbon.Now().ToDateTimeString(),
		})
		eventRequest.RespondChan <- entity.CoreResultModel{
			CoreOutModel: entity.CoreOutModel{
				GatewayOutModel: entity.GatewayOutModel{
					Data: msgBytes,
					Cmd:  protocol.RespChatroomOffline,
				},
				GatewayId:    eventRequest.GatewayId,
				MsgType:      entity.MsgTypeNormal,
				ReceiverType: entity.ReceiverTypeExclude,
				Clients:      []string{userModel.Uuid},
			},
			ResultType: entity.CoreResultTypeAll,
		}
	}
}
